package com.sailboard.iot.opm.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.sailboard.iot.opm.common.SystemCodeConstants;
import com.sailboard.iot.opm.service.qrcode.OssUtil;
import com.sailboard.iot.opm.utils.DateUtil;
import com.sailboard.iot.opm.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
@Controller
@RequestMapping(value = "/")
public class UploadUtilController {
	@RequestMapping("vi/upload")
    @ResponseBody
    public String uploadImage(@RequestParam("Filedata") MultipartFile file, HttpServletRequest request,
							HttpServletResponse response, String elementName, String bType){
    	/*MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    	CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(elementName);*/
		//MultipartFile file=(MultipartFile) request.getParameter(elementName);
		int code=200;
		String msg="";
		String result="";
		try{
		Map<String, Object> resultMap = new LinkedHashMap <String, Object> ();
     	// 判断是否为白名单内上传文件类型
	    boolean flag=false;
	    String[] allowedUploadTypes={"jpg","jpeg","tif","tiff","gif","png"};
	    String oriname= file.getOriginalFilename();
	    String typename=oriname.substring(oriname.lastIndexOf('.'),oriname.length()).toUpperCase();
	    for(String s:allowedUploadTypes){
	    	if(typename.contains(s.toUpperCase())){
	    		flag=true;
	    		break;
	    	}
	    }
	    //如果上传的文件类型非法
	    if(!flag){
	    	System.out.println(request.getRemoteAddr()+"尝试上传非法文件类型");
	    	resultMap.put("error", "上传非法文件类型");
			//return new JsonResult(ResultCode.PARAM_ERROR_CODE,"尝试上传非法文件类型",resultMap);
			 code=-1;
			 msg="上传非法文件类型";
			String resultMapString=JSONObject.toJSONString(resultMap);
			result="{\"code\":\""+code+"\",\"msg\":\""+msg+"\",\"resultMap\":"+resultMapString+"}";
			return result;
	    }
		 long size = file.getSize();
			size=size/1024;
			if(size>1000){
				resultMap.put("error", "图片大小超过1M");
				//return new JsonResult(ResultCode.PARAM_ERROR_CODE,"图片大小超过1M！",resultMap);
				code=-1;
				msg="图片大小超过1M";
				String resultMapString=JSONObject.toJSONString(resultMap);
				result="{\"code\":\""+code+"\",\"msg\":\""+msg+"\",\"resultMap\":"+resultMapString+"}";
				return result;
			}
	    String tempPath=SystemCodeConstants.STATIC_UPLOAD_URL_BD;//服务器缓存临时文件夹路径
	    String fileType=oriname.substring(oriname.lastIndexOf(".")+1);
	    String fileNameNew = UUID.randomUUID().toString() + "." + fileType;
	    File tempFolder = new File(tempPath);
        if (!tempFolder.exists()) {
        	tempFolder.mkdirs();
        }
		File tempFile = new File(tempPath+File.separator
				+ fileNameNew);
        //将上传的文件保存到临时文件夹下
		try {
			file.transferTo(tempFile);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    
	    BufferedImage checkImage;
	    int w=0;
	    int h=0;
	    try {
	    	checkImage = ImageIO.read(tempFile);
	    	w = checkImage.getWidth();
	    	h = checkImage.getHeight();
	    } catch (IOException e1) {
	    	// TODO Auto-generated catch block
	    	w=0;
	    	h=0;
	    }
		String fileUploadPath= SystemCodeConstants.STATIC_UPLOAD_URL+"/"+bType;//本地测试拼接路径
		//String fileUploadPath= SystemCodeConstants.STATIC_UPLOAD_URL+File.separator+bType;//OSS上传拼接路径
		if(StringUtils.isBlank(fileUploadPath)){
			System.out.println("业务类型不正确！");
			resultMap.put("error", "业务类型不正确");
			tempFile.delete();
			//return new JsonResult(ResultCode.PARAM_ERROR_CODE,"业务类型不正确",resultMap);
			code=-1;
			msg="业务类型不正确";
			String resultMapString=JSONObject.toJSONString(resultMap);
			result="{\"code\":\""+code+"\",\"msg\":\""+msg+"\",\"resultMap\":"+resultMapString+"}";
			return result;
		}else{
			//fileUploadPath=fileUploadPath+File.separator;//OSS用
			fileUploadPath=fileUploadPath+"/";//本地测试用
		}
	    
		String path = request.getContextPath();
		String basePath = request.getScheme() + ":"+File.separator+File.separator
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + ""+File.separator+"";
		
		String nowDate=DateUtil.getCurrentDate(0);
		String sd=nowDate.replace("-", File.separator)+File.separator;//根据日期创建子目录
		/**
		 * 切换阿里云oss存储方式
		 */
		//把日期对应的子目录连同文件名一起入库
		fileNameNew=sd+fileNameNew;
		fileNameNew=fileNameNew.replaceAll("\\\\", "/");
		
		//上传文件
		String uploadFileName=fileUploadPath+fileNameNew;
		OssUtil.uploadToOss(tempFile, uploadFileName);
		//FileUtil.copy(tempFile, uploadFile);
		tempFile.delete();
		resultMap.put("fileNameNew", fileNameNew);
		resultMap.put("fileNameOld", oriname);
		resultMap.put("fileSize", file.getSize());
		resultMap.put("fileType", fileType);
        String imageUrl=basePath+"GetImage?bt="+bType+"&fn="+fileNameNew;
		resultMap.put("imageUrl", imageUrl);
		//return new JsonResult(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG, resultMap);
			 code=200;
		      msg="上传成功";
		      String resultMapString=JSONObject.toJSONString(resultMap);
			result="{\"code\":\""+code+"\",\"msg\":\""+msg+"\",\"resultMap\":"+resultMapString+"}";
			System.out.print(result);
          return  result;
	    }catch (IllegalStateException e) {
		//	return new JsonResult(ResultCode.PARAM_ERROR_CODE, "图片大小超过1M！");
		}catch(Exception e){
		e.printStackTrace();
	    //return new JsonResult(ResultCode.PARAM_ERROR_CODE,"图片不合法！");
	}
		return result;
    }
}
